﻿using System.Linq;
using System.Linq.Expressions;

namespace System.Web.Mvc
{
	public static partial class Holovacs
	{
		public static HtmlString PasswordClearedFor<TModel, TProperty>(
			this HtmlHelper<TModel> htmlHelper,
			Expression<Func<TModel, TProperty>> expression,
			bool persistPassword,
			object htmlAttributes) where TModel : class
		{
			var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
			var propertyName = metaData.PropertyName;
			var propertyDisplayName = string.IsNullOrEmpty(metaData.DisplayName) ? metaData.PropertyName : metaData.DisplayName;
			var propertyValue = htmlHelper.ViewData.Eval(propertyName).ToStringOrEmpty();
			var textTip = metaData.Description ?? string.Empty;
			var output = string.Format("<input type=\"password\" autocomplete=\"off\" title=\"{1}\" id=\"{0}\" name=\"{0}\"",
				HttpUtility.HtmlEncode(propertyName),
				HttpUtility.HtmlEncode(textTip));
			if (htmlAttributes != null)
			{
				foreach (var kvp in htmlAttributes.GetType().GetProperties()
				 .ToDictionary(p => p.Name, p => p.GetValue(htmlAttributes, null)))
				{
					output += string.Format(" {0}=\"{1}\"", HttpUtility.HtmlEncode(kvp.Key),
					 HttpUtility.HtmlEncode(kvp.Value.ToStringOrEmpty()));
				}
			}

			if (persistPassword)
			{
				output += string.Format(" value=\"{0\"", HttpUtility.HtmlEncode(propertyValue));
			}

			output += ">";
			return new HtmlString(output);
		}

		public static HtmlString PasswordClearedFor<TModel, TProperty>(
			this HtmlHelper<TModel> htmlHelper,
			Expression<Func<TModel, TProperty>> expression,
			bool persistPassword) where TModel : class
		{
			return htmlHelper.PasswordClearedFor(expression, persistPassword, null);
		}

		public static HtmlString PasswordClearedFor<TModel, TProperty>(
			this HtmlHelper<TModel> htmlHelper,
			Expression<Func<TModel, TProperty>> expression) where TModel : class
		{
			return htmlHelper.PasswordClearedFor(expression, false);
		}

	}
}
